﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Boomerang.Common.Enumerations;
using Microsoft.Win32;
using System.Globalization;

namespace Boomerang.Common.Crm
{
    [Serializable()]
    public class CrmConnectionOptions
    {
        public string OrgName { get; set; }

        public string DiscoveryServerUrl { get; set; }

        public string CrmService { get; set; }

        public string MetadataService { get; set; }

        public CrmConnectionType AuthMode { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public string Domain { get; set; }

        public bool UseHttps { get; set; }

        public bool UseDefaultCredentials { get; set; }

        private string Protocol
        {
            get
            {
                if (!this.UseHttps)
                {
                    return "http";
                }
                return "https";
            }
        }

        public string GetCrmDiscoveryServiceUrl()
        {
            if (this.AuthMode == CrmConnectionType.IFD)
            {
                return string.Format(CultureInfo.InvariantCulture,"{0}://{1}/mscrmservices/2007/SPLA/CrmDiscoveryService.asmx", this.Protocol, this.DiscoveryServerUrl);
            }
            return string.Format(CultureInfo.InvariantCulture,"{0}://{1}/mscrmservices/2007/AD/CrmDiscoveryService.asmx", this.Protocol, this.DiscoveryServerUrl);
        }

        public ICredentials GetCrmCredentials()
        {
            if (this.AuthMode == CrmConnectionType.IFD)
            {
                return new NetworkCredential(this.UserName, this.Password);
            }
            if (!this.UseDefaultCredentials)
            {
                return new NetworkCredential(this.UserName, this.Password, this.Domain);
            }
            return CredentialCache.DefaultCredentials;
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "\tCrm Connection Options for {0} at {1} with {2} \n\t Crm Service: {3} \n\t Metadata Service {4}", this.OrgName, this.DiscoveryServerUrl, this.AuthMode, this.CrmService, this.MetadataService);
        }
 
    }



}
